package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.strategy.api.CacheService;
import com.qf.smsplatform.strategy.service.FilterChain;
import com.qf.smsplatform.strategy.util.PushMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service(value = "fee")
@Slf4j
public class FeeStrategy implements FilterChain {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMessageUtil pushMessage;

    @Override
    public boolean strategy(StandardSubmit submit) {
        log.info("【扣费策略】 扣费策略执行了....");
        //1. 获取用户剩余费用
        String feeString = cacheService.hGet(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "fee");
        if(feeString != null){
            long fee = Long.valueOf(feeString);

            //2. 获取当前短信费用
            long messageFee = submit.getFee();

            //3. 比较剩余费用是否充足（不重复发送消息，返回false）
            if(fee >= messageFee) {
                //4. 剪掉用户剩余费用需要花费的金额。
                Long remainingCost = cacheService.hincr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "fee", -messageFee);
                if(remainingCost < 0){
                    // 费用不足.
                    log.info("【扣费策略】用户剩余费用不足!!! ");
                    // 发送消息
                    pushMessage.pushLog(submit, StrategyConstants.STRATEGY_ERROR_FEE);
                    pushMessage.pushReport(submit, StrategyConstants.STRATEGY_ERROR_FEE);
                    // 添加费用
                    cacheService.hincr(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "fee", messageFee);
                    // 返回false
                    return false;
                }
                //5. 将剪掉的金额冻结，添加到缓存中。
                cacheService.incr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE + submit.getClientID(),messageFee);
                // 冻结费用成功
                log.info("【扣费策略】 扣费策略通过啦!!!.");
                return true;
            }
        }

        // 费用不足
        log.info("【扣费策略】扣费策略执行失败啦  费用不足!feeString = {}",feeString);
        // 发送消息
        pushMessage.pushLog(submit, StrategyConstants.STRATEGY_ERROR_FEE);
        pushMessage.pushReport(submit, StrategyConstants.STRATEGY_ERROR_FEE);
        // 返回false
        return false;
    }
}